package com.stockz.equity.charting.painter.chart;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.List;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import com.stockz.equity.charting.util.MathUtil;
import com.stockz.equity.charting.view.StockChartPanelSkin;
import com.stockz.equity.charting.view.StockChartPanelState;
import com.stockz.equity.charting.view.StockChart;
import com.stockz.equity.model.Bar;

@Component
@Lazy
public class AveragedChartPainter implements StockChartPainter {
	
	@Override
	public String toString(){
		return "Averaged";
	}
	
	@Override
	public void paint(Graphics2D g, StockChart view, Rectangle rectangle) {
		StockChartPanelSkin stockChartPanelSkin = view.getStockChartPanel().getStockChartPanelSkin();
		StockChartPanelState stockChartPanelState = view.getStockChartPanel().getStockChartPanelState();
		g.setColor(stockChartPanelSkin.getBarColor());
		List<Bar> barList = stockChartPanelState.getBarList();
		for(int i = stockChartPanelState.getEndIndex()-1; i >= stockChartPanelState.getStartIndex(); i--){
			if(i == stockChartPanelState.getBarList().size()-1){
				continue;
			}
			Bar bar = barList.get(i);
			Bar previousBar = barList.get(i+1);
			int x = MathUtil.fitX(rectangle.x, 
					stockChartPanelState.getTimeUnitSpace(), 
					stockChartPanelState.getEndIndex(), 
					i);
			
			int previouseAvgY = MathUtil.fitY(rectangle.y, 
					rectangle.y+rectangle.height, 
					stockChartPanelState.getMinimumPriceVisible(), 
					stockChartPanelState.getMaximumPriceVisible(), 
					previousBar.getAveragePrice(),
					stockChartPanelState.isSemiLog());
			int currentAvgY = MathUtil.fitY(rectangle.y, 
					rectangle.y+rectangle.height, 
					stockChartPanelState.getMinimumPriceVisible(), 
					stockChartPanelState.getMaximumPriceVisible(), 
					bar.getAveragePrice(),
					stockChartPanelState.isSemiLog());
			
			int higher = 0;
			int lower = 0;
			if(bar.getAveragePrice() > previousBar.getAveragePrice()){
				g.setColor(Color.green);
				higher = currentAvgY;
				lower = previouseAvgY;
			}else{
				g.setColor(Color.red);
				higher = previouseAvgY;
				lower = currentAvgY;
			}
			
			g.fillRect(x-stockChartPanelState.getTimeUnitSpace()/3, 
					higher, 
					stockChartPanelState.getTimeUnitSpace()*2/3, 
					lower - higher);
		}
	}
}
